#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "../inc/data.h"
#include "../inc/login.h"
#include "../inc/user_node.h"

user_Node_p user_Init()
{
    user_Node_p headNode = user_create();
    if (!headNode)
        return NULL;

    // 初始化空链表：头节点自循环
    headNode->next = headNode;
    headNode->prev = headNode;

    user_t user[] = {
        // 管理员
        {"admin", "123", "None", "中国国航", 1, 0},
        {"admin2", "123", "None", "东方航空", 1, 0},
        {"admin3", "123", "None", "南方航空", 1, 0},
        // 普通用户
        {"user", "123", "13900000004", "None", 0, 3000},
        {"user2", "123", "13900000005", "None", 0, 2500},
        {"user3", "123", "13900000006", "None", 0, 2800},
        {"user4", "123", "13900000007", "None", 0, 3500},
        {"user5", "123", "13900000008", "None", 0, 2000},
        {"user6", "123", "13900000009", "None", 0, 4000}};

    int length = sizeof(user) / sizeof(user[0]);

    for (int i = 0; i < length; i++)
    {
        user_Node_p node = user_create();
        if (!node)
            continue;

        // 填充数据
        node->data = malloc(sizeof(user_t));
        if (!node->data)
        {
            free(node);
            continue;
        }

        // 复制航班数据到节点
        memcpy(node->data, &user[i], sizeof(user_t));

        // 将新节点插入到链表尾部
        user_Node_p tail = headNode->prev; // 当前尾节点

        tail->next = node;
        node->prev = tail;

        node->next = headNode; // 新节点指向头节点（循环）
        headNode->prev = node; // 头节点指向新尾节点
    }

    return headNode;
}

user_Node_p user_create()
{
    user_Node_p currNode = (user_Node_p)malloc(sizeof(user_Node_t));
    currNode->data = (user_p)malloc(sizeof(user_t));
    currNode->next = currNode;
    currNode->prev = currNode;
    return currNode;
}

void user_insert(user_Node_p headNode)
{
    if (!headNode)
    {
        return;
    }

    user_Node_p newNode = user_create();
    if (!newNode)
    {
        return;
    }

    user_p userData = (user_p)malloc(sizeof(user_t));
    userData = scanf_enroll(headNode);
    newNode->data = userData;

    user_Node_p tailNode = headNode->prev;
    tailNode->next = newNode;
    newNode->prev = tailNode;
    newNode->next = headNode;
    headNode->prev = newNode;
}

user_Node_p find_userNode(user_Node_p headNode, char *username)
{
    user_Node_p currNode = headNode->next;
    while (currNode != headNode)
    {
        if (strcmp(currNode->data->username, username) == 0)
        {
            return currNode;
        }
        else
        {
            currNode = currNode->next;
        }
    }
    return NULL;
}
